package operation;

import book.BookList;

import java.util.Scanner;

public class RmoveOperation implements IOperation{
    private void del(BookList bookList,int number) {//number是坐标
        for (int j = number; j < bookList.getNumber()-1; j++) {

            bookList.setBook(bookList.getBook(j+1),j);//把后面的图书放前面
            bookList.setBook(null,j+1);//对后面的图书进行置空
            //避免内存泄露(内存浪费)  如果不置空:移动后虽然当前位置j也指向后面j+1的图书,但是如果执行
            //删除指令,把当前图书删除掉,那么j+1的指向了一个删掉了的图书,造成内存泄漏
        }
        bookList.setNumber(bookList.getNumber()-1);
        System.out.println("删除成功!");
    }
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书");
        System.out.println("请输入要删除的书名:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();

        for (int i = 0; i < bookList.getNumber(); i++) {
            if (name.equals(bookList.getBook(i).getName())) {
                del(bookList,i);
                return;
            }
        }
        System.out.println("没有要删除的图书!");
    }
}
